package com.shop.www.ssm;

import com.shop.www.JDBCUtils.JDBCUtilsByDruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BasicDao <T>{
    Connection connection = null;


    //对表格的增删改（DML）
    private QueryRunner qr = new QueryRunner();
    public int update(String sql, Object... parameters) {//增删改

        try {
            connection = JDBCUtilsByDruid.getConnection();
            //连接德鲁伊连接池
            int update = qr.update(connection,sql,parameters);
            //使用DBUTils运行sql语句
            return update;
        } catch (SQLException e) {
            throw new RuntimeException(e);
            //把编译异常变成运行异常
        }
    }

    //查询表格的多行数据，返回List
    public  List<T> querymany(String sql , Class<T> clazz , Object... parameters){
        try {
            connection = JDBCUtilsByDruid.getConnection();
            return qr.query(connection,sql,new BeanListHandler<T>(clazz),parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //查询表格的单行数据，以对象的形式返回
    public T querysingle(String sql , Class<T>clazz , Object... parameters){
        try {
            connection = JDBCUtilsByDruid.getConnection();
            return qr.query(connection,sql,new BeanHandler<T>(clazz),parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //查询表格中的单个值并返回
    public Object queryScalar(String sql ,Object... parameters){
        try {
            connection = JDBCUtilsByDruid.getConnection();
            return qr.query(connection,sql,new ScalarHandler(),parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
